<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../../plugins/element-ui/index.css"/>
    <link rel="stylesheet" href="../../styles/common.css"/>
    <link rel="stylesheet" href="../../styles/page.css"/>
    <style>
        .selectInput {
            position: relative;
            width: 100%;
            min-width: 100px;
        }

        .selectInput .flavorSelect {
            position: absolute;
            width: 100%;
            padding: 0 10px;
            border-radius: 3px;
            border: solid 1px #FF903D;
            line-height: 30px;
            text-align: center;
            background: #fff;
            top: 50px;
            z-index: 99;
        }

        .selectInput .flavorSelect .items {
            cursor: pointer;
            display: inline-block;
            width: 100%;
            line-height: 35px;
            border-bottom: solid 1px #f4f4f4;
            color: #666;
        }

        .selectInput .flavorSelect .none {
            font-size: 14px;
        }

        #food-add-app .uploadImg .el-form-item__label::before {
            content: '*';
            color: #F56C6C;
            margin-right: 4px;
        }

    </style>
</head>
<body>

<div class="addBrand-container" id="teacher-update-app">
    <div class="container">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" :inline="true" label-width="180px"
                 class="demo-ruleForm">
            <h1>编辑老师信息</h1>
            <div>
                <el-form-item label="账号名:" prop="username">
                    <el-input v-model="ruleForm.username" placeholder="请填写老师账号名" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <div>
                    <el-form-item label="头像:" prop="head" class="uploadImg">
                        <el-upload
                                class="avatar-uploader"
                                action="http://localhost:8080/common/upload"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess1"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl1" :src="imageUrl1" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </div>
            </div>
            <div>
                <div>
                    <el-form-item label="形象照:" prop="sysUser.images" class="uploadImg">
                        <el-upload
                                class="avatar-uploader"
                                action="http://localhost:8080/common/upload"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess2"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl2" :src="imageUrl2" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </div>
            </div>

            <div>
                <el-form-item label="名字:" prop="sysUser.name">
                    <el-input v-model="ruleForm.sysUser.name" placeholder="请填写老师名字" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="昵称:" prop="sysUser.nickname">
                    <el-input v-model="ruleForm.sysUser.nickname" placeholder="请填写老师昵称" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="年龄:" prop="sysUser.age">
                    <el-input v-model="ruleForm.sysUser.age" placeholder="请填写老师年龄" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="老师性别:" prop="sysUser.gender">
                    <el-radio-group v-model="ruleForm.sysUser.gender">
                        <el-radio label="男">男</el-radio>
                        <el-radio label="女">女</el-radio>
                    </el-radio-group>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="老师生日:" prop="sysUser.birthday">
                    <el-date-picker v-model="ruleForm.sysUser.birthday" type="date" placeholder="选择日期"
                                    @change="timeupdate()">
                    </el-date-picker>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="身份证号:" prop="sysUser.idNumber">
                    <el-input v-model="ruleForm.sysUser.idNumber" placeholder="请填写老师身份证号" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="老师电话:" prop="sysUser.phone">
                    <el-input v-model="ruleForm.sysUser.phone" placeholder="请填写老师电话" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="老师邮箱:" prop="sysUser.email">
                    <el-input v-model="ruleForm.sysUser.email" placeholder="请填写老师所在店铺" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="店铺名称:" prop="shopkeeperName">
                    <el-select v-model="ruleForm.shopkeeperName" placeholder="请选择店铺"
                               style="width: 150px;margin-right: 10px;">
                        <el-option label="" value="">取消选择</el-option>
                        <el-option :label="item" :value="item" v-for="(item,index) in shopkeeperNameList">
                            {{item}}
                        </el-option>
                    </el-select>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="老师标签">
                    <el-select v-model="ruleForm.sysUser.tag" multiple placeholder="请选择标签">
                        <el-option
                                v-for="tag in tagOptions"
                                :key="tag"
                                :label="tag"
                                :value="tag">
                        </el-option>
                    </el-select>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="等级:" prop="levels">
                    <el-select v-model="ruleForm.levels" placeholder="请选择">
                        <el-option
                                v-for="item in levelOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="工作时间:" prop="workTime">
                    <el-input v-model="ruleForm.work_time" placeholder="请填写老师工作时间" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="擅长:" prop="good">
                    <el-input v-model="ruleForm.good" placeholder="请填写老师的擅长" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="经历:" prop="experience">
                    <el-input v-model="ruleForm.experience" placeholder="请填写老师经历" maxlength="20"/>
                </el-form-item>
            </div>
            <div class="subBox address">
                <el-form-item>
                    <el-button @click="goBack()">取消</el-button>
                    <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                    <el-button v-if="actionType == 'add'" type="primary" class="continue"
                               @click="submitForm('ruleForm','goAnd')">
                        保存并继续添加老师
                    </el-button>
                </el-form-item>
            </div>
            <h1 style="margin-top: 30px;">老师的课程信息</h1>
            <el-table :data="tableData" stripe class="tableBox" @selection-change="handleSelectionChange"
                      max-height="500">
                <el-table-column prop="courseName" label="课程名称"></el-table-column>
                <el-table-column prop="tag" label="课程标签"></el-table-column>
                <el-table-column prop="difficulty" label="课程难度"></el-table-column>
                <el-table-column prop="room" label="教室名称"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <span style="margin-right: 10px;">{{ scope.row.status == '0' ? '停用' : '启用' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="duration" label="课程时长"></el-table-column>
                <el-table-column prop="startTime" label="开始时间"></el-table-column>
                <el-table-column prop="endTime" label="结束时间"></el-table-column>
                <el-table-column prop="courseDate" label="开课日期"></el-table-column>
                <el-table-column prop="nowPerson" label="已报人数"></el-table-column>
                <el-table-column prop="maxPerson" label="上限人数"></el-table-column>
            </el-table>
        </el-form>
    </div>
</div>
<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="../../plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../../plugins/axios/axios.min.js"></script>
<script src="../../js/request.js"></script>
<script src="../../js/validate.js"></script>
<script src="../../js/index.js"></script>
<script src="../../api/teacher.js"></script>
<script src="../../api/shop.js"></script>
<script src="../../js/common.js"></script>
<script src="../../api/shopkeeper.js"></script>
<script>
    new Vue({
        el: '#teacher-update-app',
        data() {
            return {
                baseUrl: "http://127.0.0.1:9000/jiayunplus/",
                shopkeepers: [],
                tableData: [],
                value1: '',
                imageUrl1: '',
                imageUrl2: '',
                actionType: '',
                levelOptions: [
                    {value: '1', label: '初级'},
                    {value: '2', label: '中级'},
                    {value: '3', label: '高级'}
                ],
                ruleForm: {
                    teacherId: '',
                    username: '',
                    name: '',
                    nickname: '',
                    age: '',
                    gender: '',
                    birthday: '',
                    idNumber: '',
                    phone: '',
                    email: '',
                    shopkeeperId: '',
                    tag: '',
                    levels: '',
                    workTime: '',
                    good: '',
                    experience: '',
                    head: '',
                    images: '',
                    sysUser: {
                        addr: "",
                        age: "",
                        birthday: "",
                        email: "",
                        gender: "",
                        idNumber: "",
                        name: "",
                        phone: "",
                        username: "",
                        tag:""
                    }
                },
                shopkeeperNameList: [],
                tagOptions: []
            }
        },
        computed: {
            rules() {
                return {
                    // 'name': [
                    //     {'required': true, 'message': '请填写名称', 'trigger': 'blur'}
                    // ]
                    // "name": [
                    //     {required: true, message: '请填写名称', trigger: 'blur'}
                    // ],
                    // idNumber: [
                    //     {required: true, message: '请填写身份证号', trigger: 'blur'},
                    //     {validator: this.validateIdNumber, trigger: 'blur'}
                    // ],
                    // phone: [
                    //     {required: true, message: '请填写电话', trigger: 'blur'},
                    //     {validator: this.validatePhone, trigger: 'blur'}
                    // ],
                    // email: [
                    //     {required: true, message: '请填写邮箱', trigger: 'blur'},
                    //     {type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change']}
                    // ]
                }
            }
        },
        created() {
            //和修改相关
            this.teacherId = requestUrlParam('userId');
            console.log("user id is: " + this.teacherId);
            this.actionType = this.teacherId ? 'edit' : 'add';
            if (this.teacherId) {
                this.init()
            }
            this.id = requestUrlParam('id');
            this.source = requestUrlParam('source')
            //根据标签类型获取标签名字
            getTagListByType("老师").then(
                res => {
                    this.tagOptions = res.data;
                }
            )
            this.selectClasses();
        },

        mounted() {
        },
        methods: {
            //查询店铺名称
            getAllShopkeeperName() {
                getAllShopkeeperName().then(res => {
                    this.shopkeeperNameList = res.data;
                })
            },
            turnShop(item) {
                console.log(item);
                this.ruleForm.shopkeeperId = item.shopkeeperId
            },
            handleAvatarSuccess2(res, file) {
                console.log(res.data);
                this.ruleForm.sysUser.images = res.data
                console.log(this.ruleForm.images);
                console.log(file);
                this.imageUrl2 = URL.createObjectURL(file.raw);
            },
            handleAvatarSuccess1(res, file) {
                console.log(res.data);
                this.ruleForm.head = res.data
                console.log(this.ruleForm.head);
                console.log(file);
                this.imageUrl1 = URL.createObjectURL(file.raw);
            },
            async init() {
                var _this = this
                getAllShopkeeperName().then(res => {
                    _this.shopkeepers = res.data
                    console.log(_this.shopkeepers)
                })
                //根据用户id查询老师
                queryTeacherById(this.teacherId).then(res => {
                    if (String(res.code) === '1') {
                        this.ruleForm = {...res.data};
                        this.ruleForm.status = res.data.status == '1'
                        this.ruleForm.sysUser.tag = (res.data.sysUser.tag ? res.data.sysUser.tag.split(',') : [])
                        console.log("this.ruleForm.tag" + this.ruleForm.sysUser.tag)
                        this.imageUrl1 = this.baseUrl + "" + res.data.head
                        this.imageUrl2 = this.baseUrl + "" + res.data.sysUser.images
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                    if (String(res.code) === '1') {
                        this.ruleForm = res.data;
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                })
            },
            timeupdate() {
                var t = dateFormat("yyyy-MM-dd", this.ruleForm.birthday)
                console.log(t)
                this.ruleForm.birthday = t
            },
            selectClasses() {
                console.log('Fetching classes for teacher ID:', this.teacherId);
                getByIdWithClasses(this.teacherId).then(res => {
                    console.log('API Response:', res);
                    if (String(res.code) === '1') {
                        console.log('Response data:', res.data);
                        this.tableData = Array.isArray(res.data) ? res.data : [res.data];
                    } else {
                        console.error('API Error:', res.msg);
                        this.$message.error(res.msg || '获取课程数据失败');
                        this.tableData = []; // 清空表格或显示默认数据
                    }
                }).catch(error => {
                    console.error('Request failed:', error);
                    this.$message.error('请求失败: ' + error.message);
                });
            },
            submitForm(formName, st) {
                const urlParams = new URLSearchParams(window.location.search);
                const source = urlParams.get('source') || 'default'; // 获取来源参数
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        const params = {
                            ...this.ruleForm,
                            ...this.ruleForm.sysUser.tag = this.ruleForm.sysUser.tag.toString(),
                        };
                        params.status = this.ruleForm ? 1 : 0;
                        delete params.updateTime;

                        editTeacher(params).then(res => {
                            if (res.code === 1) {
                                this.$message({
                                    message: '老师修改成功！',
                                    type: 'success',
                                    duration: 1200,  // 设置显示时间1.5秒
                                    onClose: () => {
                                        if (source === 'teacher') {
                                            window.parent.goBack();
                                        } else {
                                            window.parent.goBack();
                                        }
                                    }
                                });
                            } else {
                                this.$message.error(res.msg || '操作失败');
                            }
                        }).catch(err => {
                            this.$message.error('请求出错了：' + err);
                        });
                    } else {
                        return false;
                    }
                });
            },
            handleAvatarSuccess(response, file, fileList) {
                // 拼接down接口预览
                if (response.code === 0 && response.msg === '未登录') {
                    window.top.location.href = '../login/login.html'
                } else {
                    this.imageUrl = `/common/download?name=${response.data}`;
                    this.ruleForm.image = response.data
                }
            },
            onChange(file) {
                if (file) {
                    const suffix = file.name.split('.')[1];
                    const size = file.size / 1024 / 1024 < 2;
                    if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
                        this.$message.error('上传图片只支持 png、jpeg、jpg 格式！');
                        this.$refs.upload.clearFiles();
                        return false
                    }
                    if (!size) {
                        this.$message.error('上传文件大小不能超过 2MB!');
                        return false
                    }
                    return file
                }
            },
            goBack() {
                window.parent.menuHandle({
                    id: '4',
                    url: 'page/teacher/list.html',
                    name: '教师管理'
                }, false)

            },
            goBack2() {

                // const url = `page/stadium/detail.html?id=${encodeURIComponent(this.id)}`;
                //
                // try {
                //     if (window.parent && typeof window.parent.menuHandle === 'function') {
                //         window.parent.menuHandle({
                //             id: '12',
                //             url: url,
                //             name: '店铺详情',
                //         }, true);
                //     } else {
                //         // 备用方案
                //         window.location.href = url;
                //     }
                // } catch (error) {
                //     console.error('跳转失败:', error);
                // }
                const id = new URLSearchParams(window.location.search).get('id');
                window.parent.menuHandle(
                    {
                        id: '12',
                        url: 'page/stadium/detail.html',
                        name: '店铺详情'
                    },
                    true,
                    null,
                    {id}
                );

            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            // 验证身份证号 (18位)
            validateIdNumber(rule, value, callback) {
                if (!value) {
                    callback(new Error('请填写身份证号'));
                } else if (!/^\d{17}[\dXx]$/.test(value)) {
                    callback(new Error('请输入18位有效身份证号'));
                } else {
                    callback();
                }
            },

            // 验证手机号 (11位)
            validatePhone(rule, value, callback) {
                if (!value) {
                    callback(new Error('请填写电话'));
                } else if (!/^1[3-9]\d{9}$/.test(value)) {
                    callback(new Error('请输入11位有效手机号码'));
                } else {
                    callback();
                }
            },
            // 验证电子邮件
            validateEmail(rule, value, callback) {
                if (!value) {
                    callback(new Error('请填写邮箱'));
                } else if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value)) {
                    callback(new Error('请输入有效的邮箱地址'));
                } else {
                    callback();
                }
            },
            // 全部操作
            handleSelectionChange(val) {
                let checkArr = [];
                val.forEach((n) => {
                    checkArr.push(n.id)
                });
                this.checkList = checkArr
            },
        }
    })
</script>
</body>
</html>